using System.Windows;
using Microsoft.Win32;
using MiniTheme.Models;
using MiniTheme.Services.Interfaces;

namespace MiniTheme.Services;

public class SystemThemeMonitor : ISystemThemeMonitor
{
    private readonly IThemeService _themeService;
    private bool _isMonitoring;

    public SystemThemeMonitor(IThemeService themeService)
    {
        _themeService = themeService;
    }

    public void StartMonitoring()
    {
        if (_isMonitoring) return;
        SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged;
        _isMonitoring = true;
    }

    public void StopMonitoring()
    {
        if (!_isMonitoring) return;
        SystemEvents.UserPreferenceChanged -= OnUserPreferenceChanged;
        _isMonitoring = false;
    }

    private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
    {
        if (e.Category == UserPreferenceCategory.General && 
            _themeService.GetCurrentThemeMode() == ThemeMode.Auto)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                _themeService.ApplyTheme(ThemeMode.Auto);
            });
        }
    }
}
